import {
    Cesium3DTileset,
    HeadingPitchRange,
    Cesium3DTileContent,
    Cesium3DTileStyle,
    VerticalOrigin,
    Cartesian3,
    Cartographic,
    Matrix4,
    Matrix3,
    Math as CesiumMath,
    Transforms
} from 'cesium'

class fcHouse {
    loadedTiles: any;
    secondLoadModel:any;
    _viewer: any;

    constructor() {
        this.loadedTiles = undefined;
        this.secondLoadModel=undefined;
        this._viewer = undefined;
    }

    /**
     *加载3dtiles的数据
     * @type an-主模型，un-副模型
     * @param viewer
     */
    async load3dtiles(viewer: any,type:string, option: { "url": string, maximumScreenSpaceError: number, position: { tx: number, ty: number, tz: number } }) {
        let {url, maximumScreenSpaceError, position} = option;
        let _this = this;
        const Cesium3DTilesetOptions = {
            maximumScreenSpaceError: maximumScreenSpaceError,
            maximumNumberOfLoadedTiles: 1024,
            foveatedTimeDelay: 2,
            progressiveResolutionHeightFraction: 0.3,// 数值偏于0能够让初始加载变得模糊
            skipLevelOfDetail: true,
            maximumMemoryUsage: 1024,
            cullRequestsWhileMovingMultiplier: 10,// 值越小能够更快的剔除
            cullRequestsWhileMoving: true,   //优化选项。不要请求可能因为相机的移动而返回时未使用的磁贴
            cullWithChildrenBounds: true,  //优化选项。是否使用其子对象边界体积的联合来剔除瓷砖
            loadSiblings: true, // 如果为 true 则不会在已加载完模型后，自动从中心开始超清化模型
            immediatelyLoadDesiredLevelOfDetail: false,
            preloadWhenHidden: true,
            preferLeaves: true,
            show:type==='an' ? true:false,
            dynamicScreenSpaceErrorDensity: 0.5, // 数值加大，能让周边加载变快
            dynamicScreenSpaceErrorFactor: 1, // 不知道起了什么作用没，反正放着吧先
            dynamicScreenSpaceError: true, // 根据测试，有了这个后，会在真正的全屏加载完之后才清晰化房屋
        }
        const tileset = await Cesium3DTileset.fromUrl(url, Cesium3DTilesetOptions)
        viewer.scene.primitives.add(tileset)
        const originalSphere = tileset.boundingSphere
        const radius = originalSphere.radius

        this.changePosition(tileset,position);
        if(type==='an'){
            this.loadedTiles = tileset;
            this._viewer = viewer;
            viewer.zoomTo(tileset, new HeadingPitchRange(0.5, -0.5, radius * 3))
        }else{
            this.secondLoadModel=tileset;
        }

    }

    /**
     *        // let params = {
     *         //     tx: tx, //模型中心X轴坐标（经度，单位：十进制度）
     *         //     ty: ty, //模型中心Y轴坐标（纬度，单位：十进制度）
     *         //     tz: tz, //模型中心Z轴坐标（高程，单位：米）
     *         //     rx: rx, //X轴（经度）方向旋转角度（单位：度）
     *         //     ry: ry, //Y轴（纬度）方向旋转角度（单位：度）
     *         //     rz: rz, //Z轴（高程）方向旋转角度（单位：度）
     *         // };
     * @param tileset
     * @param options
     */
    changePosition(tileset: any, options: any) {
        let {tx, ty, tz, rx, ry, rz} = options;
        let rotationX:any,rotationY:any,rotationZ:any,m:any;
        // //旋转
        if(rx && ry && rz){
            let mx = Matrix3.fromRotationX(CesiumMath.toRadians(rx));
            let my = Matrix3.fromRotationY(CesiumMath.toRadians(ry));
            let mz = Matrix3.fromRotationZ(CesiumMath.toRadians(rz));
             rotationX = Matrix4.fromRotationTranslation(mx);
             rotationY = Matrix4.fromRotationTranslation(my);
             rotationZ = Matrix4.fromRotationTranslation(mz);
        }
        // //平移
        if(tx && ty && tz){
            let position = Cartesian3.fromDegrees(tx, ty, tz);
             m = Transforms.eastNorthUpToFixedFrame(position);
        }
        let scale = Matrix4.fromUniformScale(1);
        // //缩放
        Matrix4.multiply(m, scale, m);
        // //旋转、平移矩阵相乘
        if(rotationX){
            Matrix4.multiply(m, rotationX, m);
        }
        if(rotationY){
            Matrix4.multiply(m, rotationY, m);
        }
        if(rotationZ){
            Matrix4.multiply(m, rotationZ, m);
        }
        tileset._root.transform = m;
    }

    /**
     * 对模型进行抽屉
     */
    drawerFloor(floor: string) {
        let style = new Cesium3DTileStyle({
            color: {
                conditions: [
                    ['true', 'color("white")'],
                ],
            },
            show: '${level} !== "' + floor + '"',
        });
        if (this.loadedTiles) {
            this.loadedTiles.style = style;
            this._viewer.scene.requestRender();
            //模型必须渲染一次才能触发这
            this.loadedTiles.tileVisible.addEventListener((tile: any) => {
                // 获取 features
                const featuresLength = tile.content.featuresLength;

                for (let i = 0; i < featuresLength; i++) {
                    const feature = tile.content.getFeature(i);
                    const level = feature.getProperty("level");
                    if (level === floor) {
                        debugger
                        // console.log(feature.getComputedPosition());
                        // let smallCesium3DTileset=feature.primitive;
                        //
                        //  console.log(tile._visitedFrame,feature,feature.primitive, feature.content.getGeometry(feature.batchId));
                        // // // 创建一个新的变换矩阵，这里以平移为例
                        // var translation = Cartesian3.fromElements(0, 1, 1);
                        // var newTransform = Matrix4.fromTranslation(translation);
                        // // // 将新的变换矩阵应用到feature
                        // smallCesium3DTileset.modelMatrix = Matrix4.multiply(smallCesium3DTileset.modelMatrix , newTransform, new Matrix4());
                        // this._viewer.zoomTo(this.loadedTiles)
                        // break;
                    }
                    //  console.log(feature)
                }
            });
        }

    }

    /**
     * 改变3dtiles的颜色
     * @param floor
     */
    changeTilesStyle(floor: string) {
        const style = new Cesium3DTileStyle({
            color: {
                conditions: [
                    ['${level} === "' + floor + '"', 'color("purple", 0.8)'],
                    ['true', 'color("white")']
                ]
            }
        });
        if (this.loadedTiles) {
            this.loadedTiles.style = style;
            this._viewer.scene.requestRender();
        }
    }

    /**
     * 单独展示层
     * @param floor
     */
    showTilesBasicFllor(floor: string) {
        const style = new Cesium3DTileStyle({
            show: '${level} === "' + floor + '"',
        });
        if (this.loadedTiles) {
            this.loadedTiles.style = style;
            this._viewer.scene.requestRender();
        }
    }

    renderSecondModel(option:any,floor:string){
        if(!this.secondLoadModel){
           this.load3dtiles(this._viewer,
                'un',
                option)
        }
        const style = new Cesium3DTileStyle({
            show: '${level} === "' + floor + '"',
        });
        setTimeout(()=>{
            if (this.secondLoadModel) {
                this.secondLoadModel.style = style;
                this.secondLoadModel.show=true;
                this._viewer.scene.requestRender();
            }
        },800)
    }


}

export default new fcHouse()



